package cn.bby.jtk.bean.copier;

import org.springframework.cglib.beans.BeanCopier;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ben
 * @version 1.0
 * @date 2025/07/11
 * @since 17
 */
public interface FastBeanCopier<S,T> {
    static final Map<String, FastBeanCopier<?, ?>> beanCopierCache = new ConcurrentHashMap<>();

    void copy(S source, T target, FastCopierConverter converter);

    @SuppressWarnings("unchecked")
    static <S, T> FastBeanCopier<S, T> create(Class<S> sourceClass, Class<T> targetClass, boolean useConverter) {
        String key = sourceClass.getName() + targetClass.getName();
        return (FastBeanCopier<S, T>) beanCopierCache.computeIfAbsent(key, k -> new FastBeanCopier<S, T>() {
            final BeanCopier beanCopier = BeanCopier.create(sourceClass, targetClass, useConverter);
            @Override
            public void copy(S source, T target, FastCopierConverter converter) {
                if (useConverter) {
                    beanCopier.copy(source, target, (value, target1, context) -> {
                        return converter.convert(value, context.toString());
                    });
                } else {
                    beanCopier.copy(source, target, null);
                }
            }
        });
    }
}
